# 多平台HTTP服务器Makefile
# 支持gcc、riscv64和arm交叉编译

# 编译器设置
CC ?= gcc
CROSS_COMPILE ?= 

# 如果指定了交叉编译器前缀，则使用交叉编译器
ifneq ($(CROSS_COMPILE),)
    CC = $(CROSS_COMPILE)gcc
endif

# 编译选项
CFLAGS = -Wall -g -std=c99
LDFLAGS = -lpthread

# 调试版本编译选项
DEBUG_CFLAGS = -Wall -g -DDEBUG -O0 -std=c99

# 目标文件
TARGET = http_server

# 源文件
SRCS = main.c server_functions.c cgi_functions.c

# 头文件
HDRS = server_functions.h

# 目标文件列表
OBJS = $(SRCS:.c=.o)

# 默认目标
all: $(TARGET)

# 编译目标
$(TARGET): $(OBJS)
	$(CC) $(CFLAGS) -o $(TARGET) $(OBJS) $(LDFLAGS)
	@echo "编译完成: $(TARGET) (使用编译器: $(CC))"

# 交叉编译目标支持
http_server_riscv64: $(OBJS)
	$(CC) $(CFLAGS) -o http_server_riscv64 $(OBJS) $(LDFLAGS)
	@echo "编译完成: http_server_riscv64 (使用编译器: $(CC))"

http_server_arm: $(OBJS)
	$(CC) $(CFLAGS) -o http_server_arm $(OBJS) $(LDFLAGS)
	@echo "编译完成: http_server_arm (使用编译器: $(CC))"

# 编译源文件为目标文件
%.o: %.c $(HDRS)
	$(CC) $(CFLAGS) -c $< -o $@

# 调试版本
debug: CFLAGS = $(DEBUG_CFLAGS)
debug: clean $(TARGET)
	@echo "调试版本编译完成: $(TARGET)"

# GCC本地编译
gcc:
	@$(MAKE) CROSS_COMPILE= CC=gcc $(TARGET)
	@echo "GCC本地编译完成"

# RISC-V 64位交叉编译
riscv64:
	@$(MAKE) CROSS_COMPILE=riscv64-anyka-linux-musl- TARGET=http_server_riscv64 http_server_riscv64
	@echo "RISC-V 64位交叉编译完成"

# ARM交叉编译
arm:
	@$(MAKE) CROSS_COMPILE=arm-nextvpu-linux-gnueabihf- TARGET=http_server_arm http_server_arm
	@echo "ARM交叉编译完成"

# 清理编译产物
clean:
	@rm -f $(OBJS) http_server http_server_* *.o
	@rm -rf *.dSYM
	@echo "清理完成"

# 安装到系统目录
install: $(TARGET)
	install -m 755 $(TARGET) /usr/local/bin/
	@echo "安装完成: /usr/local/bin/$(TARGET)"

# 卸载
uninstall:
	rm -f /usr/local/bin/http_server
	@echo "卸载完成"

# 运行服务器
run: $(TARGET)
	./$(TARGET)

# 编译所有平台版本
all-platforms: gcc riscv64 arm
	@echo "所有平台编译完成"

# 显示帮助信息
help:
	@echo "HTTP服务器编译系统"
	@echo "可用目标:"
	@echo "  all         - 默认编译 (gcc)"
	@echo "  gcc         - GCC本地编译"
	@echo "  riscv64     - RISC-V 64位交叉编译"
	@echo "  arm         - ARM交叉编译"
	@echo "  debug       - 调试版本编译"
	@echo "  all-platforms - 编译所有平台版本"
	@echo "  clean       - 清理编译产物"
	@echo "  run         - 运行服务器"
	@echo "  install     - 安装到系统"
	@echo "  help        - 显示此帮助信息"
	@echo ""
	@echo "自定义交叉编译:"
	@echo "  make CROSS_COMPILE=your-toolchain-prefix- TARGET=your-target-name"

# 伪目标声明
.PHONY: all gcc riscv64 arm debug clean run install uninstall all-platforms help